package com.kate.ioc.config;

import com.github.pagehelper.PageInterceptor;
import org.apache.commons.dbcp.BasicDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.GenericApplicationContext;

import javax.sql.DataSource;

/**
 * @author 新梦想.陈超
 * @version 2021.2
 * @Description: {TODO}
 * @date 2022/5/7 下午4:26
 */

@Configuration
@MapperScan("com.kate.ioc.mapper")
public class AppConfig {

    public DataSource dataSource(){
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUsername("root");
        dataSource.setUrl("jdbc:mysql://localhost:3306/ssm_db?useUnicode=true&amp&characterEncoding=utf-8");
        dataSource.setPassword("abc123456");
        return dataSource;
    }


    @Autowired
    private GenericApplicationContext genericApplicationContext;
    @Bean
    public SqlSessionFactory sqlSessionFactory() throws Exception {
        SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
        factoryBean.setDataSource(dataSource());
        //配置maper映射文件

//        factoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:com/xmx/mapper/*.xml"));

//        Resource resource =new ClassPathResource("classpath*:sqlmap/*Mapper.xml");
//        factoryBean.setMapperLocations(resource);

        factoryBean.setMapperLocations(genericApplicationContext.
                getResources("classpath*:sqlmap/*Mapper.xml"));
        //别名
        factoryBean.setTypeAliasesPackage("com.kate.ioc.entity");

        //驼峰映射
        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
        configuration.setMapUnderscoreToCamelCase(true);
        factoryBean.setConfiguration(configuration);
        //分页插件
        factoryBean.setPlugins(pageInterceptor());
        return factoryBean.getObject();
    }

    public PageInterceptor pageInterceptor(){
        return new PageInterceptor();
    }


}